import ch.sfug.events.ProgressEvent;
import ch.sfug.events.TimerEvent;
import ch.sfug.net.loader.XMLLoader;
import ch.sfug.utils.Timer;

/**
 * enhance the default xmlloader with a progress event
 * @author loop
 */
class ch.sfug.net.loader.XMLProgressLoader extends XMLLoader {

	private var timer:Timer;
	
	/**
	 * constructor
	 * @param xmlUrl the xml url
	 * @param noCache (optional) if true the loaded url will contain a random number to prevent caching. default is false.
	 */
	public function XMLProgressLoader( xmlUrl:String, noCache:Boolean ) {
		super( xmlUrl, noCache );
		this.timer = new Timer( 100, 0 );
		this.timer.addEventListener( TimerEvent.TIMER, calcProgress, this );
	}

	/**
	 * extends the super load function to start the progresscalculator
	 * @param xmlUrl (optional) reassign url before loading
	 * @param noCache (optional) if true the loaded url will contain a random number to prevent caching. default is false.
	 */
	public function load( xmlUrl:String, noCache:Boolean ):Void {
		super.load( xmlUrl, noCache );
		this.timer.start();
	}

	/**
	 * extends the super load function to start the progresscalculator
	 * @param lv a loadvars object to send to the url and get the result back
	 * @param method (optional) the method how to send the vars. default is POST.
	 * @param xmlUrl (optional) reassign url before loading
	 * @param noCache (optional) if true the loaded url will contain a random number to prevent caching. default is false.
	 */
	public function sendVar( lv:LoadVars, method:String, xmlUrl:String, noCache:Boolean ):Void {
		super.sendVar( lv, method, xmlUrl, noCache );
		this.timer.start();
	}

	/**
	 * extends the super load function to start the progresscalculator
	 * @param send_xml a xml file to send to the url.
	 * @param xmlUrl (optional) reassign url before loading
	 * @param noCache (optional) if true the loaded url will contain a random number to prevent caching. default is false.
	 */
	public function sendXML( send_xml:XML, xmlUrl:String, noCache:Boolean ):Void {
		super.sendXML( send_xml, xmlUrl, noCache );
		this.timer.start();
	}

	/**
	 * extends the super function to stop the progress calculation
	 */
	private function onLoad( success:Boolean ):Void {
		calcProgress();
		super.onLoad( success );
		this.timer.stop();
		this.timer.reset();
	}

	/**
	 * creates a xml progress event
	 */
	private function calcProgress():Void {
		if( xml.getBytesLoaded() != undefined && xml.getBytesTotal() != undefined ) {
			dispatchEvent( new ProgressEvent( ProgressEvent.PROGRESS, xml.getBytesLoaded(), xml.getBytesTotal() ) );
		}
	}

}